﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// Java 列表显示类
    /// </summary>
    public class JavaViewsListHelper
    {

        /// <summary>
        /// 根据表名创建列表显示类
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateViewListClass(string strFilePath,string strProjectName,string strHtmlInputList, string strTableName,string strTableComment)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");

            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);
            
            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id
            string strJavaPrimaryKey = CommonHelper.GetTableNameUpper(strPrimaryKey);
            strJavaPrimaryKey = CommonHelper.GetTableNameUpper(strJavaPrimaryKey);//News
            strJavaPrimaryKey = CommonHelper.GetTableNameFirstLowerSecondUpper(strJavaPrimaryKey);

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);//News
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes

            string strTableComment2 = CommonHelper.GetColumnKeyComment(strTableComment);

            string strNewPath = strFilePath + "\\resources\\static\\" + strTableNameLower + "\\webpage";
            if (!Directory.Exists(strNewPath))
            {
                Directory.CreateDirectory(strNewPath);
            }

            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            StreamWriter sw = new StreamWriter(strNewPath + "\\" + strTableNameSpec + "List.html", false, utf8WithoutBom);

            sw.WriteLine("<!DOCTYPE html>");
            sw.WriteLine("<html>");
            sw.WriteLine("<head>");
            sw.WriteLine("    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">");
            sw.WriteLine("    <meta charset=\"utf-8\"/>");
            sw.WriteLine("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
            sw.WriteLine("    <link rel=\"stylesheet\" href=\"../../../layuiadmin/layui/css/layui.css\" media=\"all\"/>");
            sw.WriteLine("    <link rel=\"stylesheet\" href=\"../../../layuiadmin/style/admin.css\" media=\"all\"/>");
            sw.WriteLine("    <link rel=\"stylesheet\" href=\"../../../css/common/loader.css\" media=\"all\"/>");
            sw.WriteLine("    <link rel=\"stylesheet\" href=\"../../../css/common/tablepage.css\" media=\"all\"/>");
            sw.WriteLine("</head>");
            sw.WriteLine("<body>");
            sw.WriteLine("<div class=\"layui-fluid\">");
            sw.WriteLine("    <div class=\"layui-card\">");
            sw.WriteLine("        <div class=\"layui-form layui-card-header layuiadmin-card-header-auto\" id=\"searchForm\">");
            sw.WriteLine("            <div class=\"layui-form-item\">");
            sw.WriteLine(GetSearchItemList(strTableName));
            sw.WriteLine("");
            sw.WriteLine("                <div class=\"layui-inline\">");
            sw.WriteLine("                    <button class=\"layui-btn layuiadmin-btn-sm\" lay-submit lay-filter=\"searchSubmit\">查询</button>");
            sw.WriteLine("                </div>");
            sw.WriteLine("            </div>");
            sw.WriteLine("        </div>");
            sw.WriteLine("        <div class=\"layui-card-body\">");
            sw.WriteLine("            <table id=\"dataList\" lay-filter=\"dataList\"></table>");
            sw.WriteLine("        </div>");
            sw.WriteLine("    </div>");
            sw.WriteLine("</div>");
            sw.WriteLine("<div type=\"text/html\" id=\"toolbar\" style=\"display:none\">");
            sw.WriteLine("    <div class=\"layui-btn-container\">");
            sw.WriteLine("        <button data-grant=\"system:role:add\" class=\"layui-btn layui-btn-sm\" lay-event=\"add\"><i class=\"layui-icon\">&#xe654;</i>新增");
            sw.WriteLine("        </button>");
            sw.WriteLine("    </div>");
            sw.WriteLine("</div>");
            sw.WriteLine("<div type=\"text/html\" id=\"trTool\" style=\"display:none\">");
            sw.WriteLine("    <a data-grant=\"system:role:edit\" class=\"layui-btn layui-btn-normal layui-btn-xs\" lay-event=\"edit\"><i");
            sw.WriteLine("            class=\"layui-icon layui-icon-edit\"></i>编辑</a>");
            sw.WriteLine("    <a data-grant=\"system:role:remove\" class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\"><i");
            sw.WriteLine("            class=\"layui-icon layui-icon-delete\"></i>删除</a>");
            sw.WriteLine("</div>");
            sw.WriteLine("<script type=\"text/html\" id=\"statusTpl\">");
            sw.WriteLine("    <input type=\"checkbox\" name=\"status\" value=\"{{d.typeId}}\" title=\"启用\" lay-filter=\"status\" {{ d.typeStatus == '1' ? 'checked' : '' }}>");
            sw.WriteLine("</script>");
            sw.WriteLine("<script src=\"../../../layuiadmin/layui/layui.js\"></script>");
            sw.WriteLine("<script type=\"text/javascript\" src=\"../../../lib/jQuery-2.2.0.min.js\"></script>");
            sw.WriteLine("<script>");
            sw.WriteLine("    layui.config({");
            sw.WriteLine("        base: '../../../layuiadmin/' //静态资源所在路径");
            sw.WriteLine("    }).extend({");
            sw.WriteLine("        webplus: 'lib/webplus'//主入口模块");
            sw.WriteLine("    }).use(['table', 'form', 'webplus'], function () {");
            sw.WriteLine("        var $ = layui.$,");
            sw.WriteLine("            webplus = layui.webplus,");
            sw.WriteLine("            form = layui.form,");
            sw.WriteLine("            table = layui.table;");
            sw.WriteLine("        var cols = [[{");
            sw.WriteLine("            type: 'numbers',");
            sw.WriteLine("            title: '序号',");
            sw.WriteLine("            width: 50");
            sw.WriteLine("        },");
            sw.WriteLine(GetTableColsList(strTableName));
            sw.WriteLine("            {");
            sw.WriteLine("                title: '操作',");
            sw.WriteLine("                toolbar: '#trTool',");
            sw.WriteLine("                fixed: 'right',");
            sw.WriteLine("                width: 200");
            sw.WriteLine("            }]];");
            sw.WriteLine("        webplus.init('newsTypes/list', cols)");
            sw.WriteLine("        //监听行工具事件");
            sw.WriteLine("        table.on('tool(dataList)', function (rowObj) {");
            sw.WriteLine("            switch (rowObj.event) {");
            sw.WriteLine("                case 'edit':");
            sw.WriteLine("                    webplus.openEditWindow('" + strTableNameSpec + "Edit.html', '编辑', rowObj, 'typeId', '', '500', '350');");
            sw.WriteLine("                    break;");
            sw.WriteLine("                case 'del':");
            sw.WriteLine("                    webplus.removeRow('" + strTableNameSpec + "/remove', rowObj, 'typeId');");
            sw.WriteLine("                    break;");
            sw.WriteLine("            }");
            sw.WriteLine("        });");
            sw.WriteLine("        //监听启用操作");
            sw.WriteLine("        form.on('checkbox(status)', function(obj){");
            sw.WriteLine("            if(webplus.checkFormEditMode(obj)){");
            sw.WriteLine("                var status=\"0\";");
            sw.WriteLine("                if(obj.elem.checked){");
            sw.WriteLine("                    status=\"1\";");
            sw.WriteLine("                }");
            sw.WriteLine("");
            sw.WriteLine("                var typeId=obj.value;");
            sw.WriteLine("                var params={};");
            sw.WriteLine("                params.typeId=typeId;");
            sw.WriteLine("                params.typeStatus=status;");
            sw.WriteLine("                webplus.doAjax(\"" + strTableNameSpec + "/update\",params,\"\",\"0\");");
            sw.WriteLine("            }");
            sw.WriteLine("");
            sw.WriteLine("        });");
            sw.WriteLine("        //监听表头按钮事件");
            sw.WriteLine("        table.on('toolbar(dataList)', function (obj) {");
            sw.WriteLine("            switch (obj.event) {");
            sw.WriteLine("                case 'add':");
            sw.WriteLine("                    //打开添加弹出框");
            sw.WriteLine("                    webplus.openWindow('" + strTableNameSpec + "Add.html', '新增', '500', '350');");
            sw.WriteLine("                    break;");
            sw.WriteLine("            }");
            sw.WriteLine("        });");
            sw.WriteLine("");
            sw.WriteLine("    });");
            sw.WriteLine("</script>");
            sw.WriteLine("</body>");
            sw.WriteLine("</html>");


            sw.Close();

        }



        /// <summary>
        /// 获取搜索字段列表
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchItemList(string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释


                    if (strColumnComment.Contains("{搜索}"))
                    {
                        string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                        string strValue = "                <div class=\"layui-inline\">\r\n";
                        strValue += "                    <label class=\"layui-form-label\">" + strColumnComment2 + "</label>\r\n";
                        strValue += "                    <div class=\"layui-input-inline\">\r\n";
                        strValue += "                        <input type=\"text\" maxlength=\"20\" id=\"" + strColumnName + "\" name=\"" + strColumnName + "\" placeholder=\"请输入" + strColumnComment2 + "\" autocomplete=\"off\" class=\"layui-input\">\r\n";
                        strValue += "                    </div>\r\n";
                        strValue += "                </div>\r\n";

                        strReturnValue += strValue;
                    }

                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取表格显示字段列表
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetTableColsList(string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                    string strJavaColumnName = CommonHelper.GetTableNameUpper(strColumnName);
                    strJavaColumnName = CommonHelper.GetTableNameUpper(strJavaColumnName);//News
                    strJavaColumnName = CommonHelper.GetTableNameFirstLowerSecondUpper(strJavaColumnName);

                    string strValue = "                {\r\n";
                    strValue += "                    field: \"" + strJavaColumnName + "\",\r\n";
                    strValue += "                    title: \"" + strColumnComment2 + "\",\r\n";
                    if (strColumnName == "createdAt" || strColumnKey == "PRI")
                    {
                        //主键和日期需要排序
                        strValue += "                    sort: !0,\r\n";
                    }
                    else if (strColumnKey == "PRI")
                    {
                        //主键设置宽度
                        strValue += "                    width: 80,\r\n";
                    }
                    else if (strColumnName == "createdAt")
                    {
                        //日期设置宽度及格式
                        strValue += "                    width: 180,\r\n";
                        strValue += "                    templet: \"<div>{{layui.util.toDateString(d.created_at, 'yyyy-MM-dd HH:mm')}}</div>\",\r\n";
                    }
                    else if (strColumnName.ToLower().Contains("name"))
                    {
                        strValue += "                    minWidth: 300,\r\n";
                    }
                    else if (strColumnName.ToLower().Contains("status"))
                    {
                        //设置状态可编辑
                        strValue += "                    templet: \"#statusTpl\",\r\n";
                    }
                    strValue += "                },\r\n";

                    strReturnValue += strValue;

                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }


    }
}
